//
//  ZBookShelfViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/4/30.
//  Copyright © 2019 macfeel. All rights reserved.
//

#import "ZBookShelfViewController.h"
//#import "ReadCollectionViewCell.h"
#import "ZBookShelfCollectionCell.h"
#import "BookshelfModel.h"
#import "ZBookMsgDetailVC.h"
#import "HomeModel.h"///这里包含着MModle
#import "UIButton+ImageTitleSpacing.h"

@interface ZBookShelfViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    NSInteger myRow;
}
@property(nonatomic,strong)UICollectionView *collectionView;


@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *deleteArray;
@property (nonatomic, strong) UIButton *rightBtn; //右边的按钮
@property (nonatomic, assign) BOOL inEditState; //是否处于编辑状态
@property (nonatomic,strong) UIView *bgView;
@property (nonatomic,strong) UIButton *deleteButton;

@end

#define kLineNumber 3
#define kBarHeight 40

///这个cellid 全局不能重复
//NSString *const cellid = @"read";
#define cellId @"read"

@implementation ZBookShelfViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self.navigationItem setItemWithTitle:@"我的书架" textColor:kNavigationTitleColor fontSize:18 itemType:center];
//    [self showNoDataImageView:@"none" withTitle:@"暂无数据哦"];
    self.dataArray = [NSMutableArray array];
    self.deleteArray = [NSMutableArray array];
//    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 40, 40) title:@"编辑" Image:@"" selectedIMG:@"" tartget:self action:@selector(editAction:)];
    
    [self.view addSubview:self.collectionView];
    [self addRightBarButtonItem]; //添加右边的编辑按钮
    [self createUI];
    self.bgView.hidden = YES;
    // Do any additional setup after loading the view.
}
- (void) createUI{
    self.bgView = [[UIView alloc] init];
    self.bgView.backgroundColor = kWhiteColor;
    [self.view addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, 44));
        make.bottom.equalTo(self.view.mas_bottom);
        make.centerX.equalTo(self.view);
    }];
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor colorWithHex:@"f5f5f5"];
    [self.bgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, 1));
        make.top.equalTo(self.bgView);
        make.centerX.equalTo(self.bgView);
    }];
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.deleteButton.backgroundColor = kWhiteColor;
    [self.deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    [self.deleteButton setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
    [self.deleteButton setTitleColor:[UIColor colorWithHex:@"666666"] forState:UIControlStateNormal];
    self.deleteButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.deleteButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:8];
    [self.bgView addSubview:self.deleteButton];
    
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ScreenWidth);
        make.bottom.bottom.equalTo(self.bgView.mas_bottom);
        make.top.equalTo(lineView.mas_bottom);
        make.centerX.equalTo(self.view);
    }];
    [self.deleteButton addTarget:self action:@selector(deleteClickBtn) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 点击删除
- (void)deleteClickBtn{
    
    NSLog(@"deleteArray------:%@",self.deleteArray);
    BookshelfModel *model;
    for (NSDictionary *dic in self.deleteArray) {
        model = [BookshelfModel mj_objectWithKeyValues:dic];
    }
    
    NSDictionary *dic = @{@"classType":model.classType,@"collectionId":model.collectionId,@"userInfo.id":[UserInfoSave shareInstance].uid?:@"",@"ids":model.ids,@"addType":@"2"};
    
    
    [ZNetworkService postRequestWithBaseUrl:kBookshelfupdateBookUrl setParameters:dic success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
        }
    } fail:^(NSError *error) {
    } delegater:nil];
}
#pragma mark - 添加右边的编辑按钮

- (void)addRightBarButtonItem
{
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(rightBarButtonItemAction:) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn sizeToFit];
    [_rightBtn setTitle:@"完成" forState:UIControlStateSelected];
    [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];    [_rightBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    //将leftItem设置为自定义按钮
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc] initWithCustomView: _rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}
#pragma mark - 右边的编辑按钮方法

- (void)rightBarButtonItemAction:(UIButton *)barButton{
    if (!self.inEditState) {//点击了编辑
        self.inEditState = YES;
        self.bgView.hidden = NO;
        self.rightBtn.selected = YES;
        self.collectionView.allowsSelection = NO;
    } else{//点击了完成
        self.inEditState = NO;
        self.bgView.hidden = YES;
        self.rightBtn.selected = NO;
        self.collectionView.allowsSelection = YES;
        //此处可以调用网络请求，把排序完之后的传给服务端
//        [self loadData];
        NSLog(@"点击了完成按钮");
    }
    for (ZBookShelfCollectionCell *cell in self.collectionView.visibleCells) {
        cell.inEditState = self.inEditState;
    }
}
- (void)viewWillAppear:(BOOL)animated{
    [self loadData];
    myRow = -1;
}

- (void)loadData{
    //
    WeakStament(ws);
//   NSString *currentUser = [[NSUserDefaults standardUserDefaults]objectForKey:kUserId];
    //如果需要加  加载更多，这里就需要进行判断了
    [self.dataArray removeAllObjects];
    
    NSDictionary *dic = @{@"pageIndex":@"1",@"pageSize":@"10",@"userInfo.id":[UserInfoSave shareInstance].uid?:@""};
    
    [ZNetworkService postRequestWithBaseUrl:kBookshelfListUrl setParameters:dic success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSArray *arr = result[@"result"];
            for (NSDictionary *dic in arr) {
                BookshelfModel *model = [BookshelfModel mj_objectWithKeyValues:dic];
                [ws.dataArray addObject:model];
            }
            [ws.collectionView reloadData];
            [ws endRefresh];
        }
    } fail:^(NSError *error) {
        [self endRefresh];
    } delegater:nil];
}

//流式布局
- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //整个 section 的四周边界的margin
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    ///45行代码和  ScreenWidth-4（minimumLineSpacing*2）形成中间的小横线
    layout.minimumLineSpacing = 1.f;
    layout.minimumInteritemSpacing = 0.f;
    //    layout.headerReferenceSize = CGSizeMake(kScreenWidth, SectionHeaderHeight);
    layout.itemSize = CGSizeMake((ScreenWidth-2)/3, ScreenWidth>375?200:180);
    return layout;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-ScreenHeightFlex) collectionViewLayout:[self flowLayout]];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self registerCell];
        WeakStament(ws);
        _collectionView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
            [ws loadData];
        }];
        
        _collectionView.backgroundColor = kWhiteColor;
    }
    return _collectionView;
}

- (void)registerCell {

    [_collectionView registerClass:[ZBookShelfCollectionCell class] forCellWithReuseIdentifier:cellId];
    
}



#pragma datasource


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}



-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    BookshelfModel *model = self.dataArray[indexPath.row];
    ZBookShelfCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

//    ReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kPicServerUrl,model.bookInfo[@"photo"]]] placeholderImage:nil];
    //二重字典
    YYLog(@"%@",model.bookInfo[@"photo"]);
    cell.titleLab.text = model.bookInfo[@"name"];
    //是否处于编辑状态，如果处于编辑状态，出现按钮，否则隐藏
    cell.inEditState = self.inEditState;

    [cell sizeToFit];
    
    if (myRow == indexPath.row) {
        [cell setChecked:YES];
    }
    else {
        [cell setChecked:NO];
    }
    [cell.button addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
#pragma mark - 点击button的方法

- (void)btnClick:(UIButton *)sender event:(id)event{
    //获取点击button的位置
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:_collectionView];
    NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:currentPoint];
    [self.deleteArray removeAllObjects];
    if (myRow == indexPath.row) {
        myRow = -1;
        [self.deleteArray removeObject:self.dataArray[indexPath.row]];
    }
    else {
        myRow = indexPath.row;
        [self.deleteArray addObject:self.dataArray[indexPath.row]];
    }
    [self.collectionView reloadData];
}


#pragma mark - delegate
//cell尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//    CGFloat width=ScreenWidth/kLineNumber;
//    return CGSizeMake(width, width*1.2);
//}

///section header 尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(ScreenWidth, SectionHeaderHeight-20);
//}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BookshelfModel *model = self.dataArray[indexPath.row];
    ZBookMsgDetailVC *msg = [ZBookMsgDetailVC new];
    MidModel *MModel = [MidModel new];
    MModel.name = model.bookInfo[@"name"];
    MModel.picUrl = [NSString stringWithFormat:@"%@%@",kPicServerUrl,model.bookInfo[@"photo"]];
    msg.MModel = MModel;
    [self.navigationController pushViewController:msg animated:YES];
}


- (void)endRefresh{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}
@end
